package org.grow.chat.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.chat.entity.Speech;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.core.AbstractMessageSendingTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2022/1/9
 */
// MessageMapping /ws
@Controller
public class AnyMessageHandler {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    @MessageMapping("/normal")
// 经过验证  mm注解所在组件必须是controller注解或restController
// 只使用component service等 不可以生效 会报如下信息
// No matching message handler methods.
    public void sign(String jsonData){
        System.out.println("stomp 消息体 "+jsonData);
//        topic 数据库 general 临时表中 也是 前端需要一直监听的地址
//
        simpMessagingTemplate.convertAndSend("/union/general",jsonData);

    }
    @Scheduled(cron = "0 */1 * * * *")
    public void task(){
        System.out.println("定时任务一分钟跑一个");
        simpMessagingTemplate.convertAndSend("/exchange/world/","测试rabbit主机");
//        simpMessagingTemplate.convertAndSend("/union/general",
//                "服务器定时任务数据");
    }

    @MessageMapping("/unionChannel")
    public void unionWords (Speech speech) {
        System.out.println(speech);
        String unionName = speech.getUnionName();
        String r = null;
        try {
            r = objectMapper.writeValueAsString(speech);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        simpMessagingTemplate.convertAndSend("/union/"+unionName, r);
    }
    @MessageMapping("/worldChannel")
    public void worldWords(Speech speech){
        System.out.println("==============世界发言"+speech);
        System.out.println("==============世界发言"+speech);
        System.out.println("==============世界发言"+speech);
        String r = null;
        try {
            r = objectMapper.writeValueAsString(speech);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        simpMessagingTemplate.convertAndSend("/exchange/world/", r);
    }

}
